import Router from 'next/router'
import {Component} from 'react'
import {connect} from 'react-redux'
import SearchResult from './Result';
import {searchName, commonChangeWay} from '../../store/actions'
import { SearchBar,  Toast } from 'antd-mobile';
import styles from './SearchBar.module.scss';
import { IProps, State } from "./type"

class Search extends Component<IProps, State>{
  searchBlock: any;
  constructor(props) {
    super(props);
    this.state = {
      value: '',
      onFocusType: false,
    };
  }
  searchGo(str) {
    const {searchName} = this.props
    searchName({
      str, showCount: 5, isServer: false
    })
  }
  // handleClick() {
  //   this.manualFocusInst.focus();
  // }
  isSearch() {
    this.setState({
      onFocusType: true
    })
    this.props.commonChangeWay({
      searchType: true
    })
  }
  handlFocusBlur() {
    this.setState({
      onFocusType: !this.state.onFocusType
    })
    this.props.commonChangeWay({
      searchType: false
    })
  }
  choiceBrand(item) {
    const {commonChangeWay} = this.props
    commonChangeWay({topSeachName: item.name})
    this.searchBlock.state.value = item.name;
    Router.push({
      pathname: item.linkUrl, 
      query: { id: item.id }
    }, `${item.linkUrl}/${item.id}?indexType=${item.theIndex}` )
    Toast.loading('加载中', 0);
    this.props.commonChangeWay({
      searchType: false
    })
  }
  render() {
    const {onFocusType} = this.state;
    let {searchData, mbiType} = this.props;
    if (searchData === null || searchData === undefined ) {
      searchData = [];
    } else {
      searchData.map((item, index)=>{
        if (item.theIndex === '1102') {
          item.linkUrl = `/hotelindex`
        } else {
          item.linkUrl = `/brandindex`
        }
      })
    }
    
    return (
      <section className={onFocusType ? styles['search-active'] : styles['search-box']}>
        <SearchBar
          placeholder="搜索"
          onSubmit={value => this.searchGo(value)}
          ref={ref => this.searchBlock = ref}
          // onClear={value => console.log(value, 'onClear')}
          onFocus={() => this.isSearch() }
          // onBlur={() => this.handlFocusBlur()}
          onCancel={() => this.handlFocusBlur()}
          // onChange={(value) => {
          //   this.onChange(value)
          // }}
        />
        <SearchResult 
          searchData={searchData} 
          mbiType={mbiType}  
          goDetailed={(item) => {this.choiceBrand(item)}} 
        />
      </section>);
  }
}

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
     searchName: (data) => dispatch(searchName(data)),
     commonChangeWay: (data) => dispatch(commonChangeWay(data)),
  };
}

const mapStateToProps = (state, ownProps) => {
  return {
    searchData: state.searchData,
    topSeachName: state.topSeachName,
    mbiType: state.mbiNavigation
  };
};


export default connect(mapStateToProps, mapDispatchToProps)(Search)
